package com.chap17.completablefuture;

import lombok.extern.slf4j.Slf4j;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * <code>Demo11</code>
 * </p>
 *
 * @author junbao3
 * TODO
 * @date 2023-05-10 10:14
 * Copyright (C) 2021 IFlyTek. All rights reserved.
 */
@Slf4j
public class Demo12 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture.supplyAsync(() -> {
            int number = new Random().nextInt(3)+1;
            sleep(number, TimeUnit.SECONDS);
            log.debug("第一阶段：{}", number);
            return number;
        }).thenAcceptBoth(CompletableFuture.supplyAsync(()->{
            int number = new Random().nextInt(3)+1;
            sleep(number, TimeUnit.SECONDS);
            log.debug("第二阶段：{}", number);
            return number;
        }),(n1,n2)->{log.debug("最终结果：{}",(n1+n2));}).join();
    }

    private static void sleep(int number, TimeUnit seconds) {
        try {
            seconds.sleep(number);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
